package org.vgou.page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.vgou.util.WebConstants;

public class PageUntils {

	protected final static Log logger = LogFactory.getLog(PageUntils.class);
	
	/**
	 * 
	 * @param request
	 * @param currentPage
	 * 			当前为第几页了
	 * @param perPage
	 * 			每一页有多少条记录
	 * @param total
	 * 			一其有多少条记录
	 * @param param
	 * 			分页的参数
	 * @param pageBarName
	 * 			用来显示的分页条的名字，一般我们用page，然后在显示页面用${page} ，但是有些页面一个页面有两个分页条，故要起一个不同的名字来区分一下
	 * @return
	 */
	public static Page getPageBar(HttpServletRequest request, int currentPage , int perPage , int total , String param , String pageBarName){
		String contextPath = request.getContextPath();
		HttpSession session = request.getSession();
		String realPath = session.getServletContext().getRealPath("/");
		String templatePath = WebConstants.TEMPLATEPATH;
		String templateName = "page.ftl";
		
		Page page = new Page();
		
		try {
//			int total = enterpriseService.getAllEnterpriseCount(0,null, 1);
			PageHelper pageHelper = new PageHelper(request);
			perPage = pageHelper.doCustomPerPage(perPage);

			page.setUrl(request.getRequestURI());

			page.setPerPage(perPage);

			/**
			 * 此处处理页码为负数、大于总页数、删除最后一页数据后应转向最后一页的页码-1、页码非数字
			 */
			int cPage = pageHelper.getCpage(total, perPage, currentPage);
			page.setPage(cPage);
			page.setRealPath(realPath);
			page.setPageTemplatePath(templatePath);
			page.setPageTemplate(templateName);
			page.setTotal(total);
			page.setContextPath(contextPath);
			page.setStartRs((cPage - 1) * perPage);
			
			//分页需要的参数
			if(param != null && !"".equals(param)){
				page.setParam(param);
			}
			
			request.setAttribute(pageBarName , pageHelper.getPageBreakStr(page));
			
			return page;
		}
		catch (Exception e) {
			page = null;
			logger.error("获取分页条里发生异常 :" + e.getMessage());
		}
		return page;
	}
}
